<template>
  <div class="image-to-gif-page">
    <div class="gif-container">
      <h1>多图合成GIF</h1>
      
      <el-upload
        class="upload-area"
        action="#"
        list-type="picture-card"
        :auto-upload="false"
        :on-change="handleFileChange"
        multiple
      >
        <el-icon><Plus /></el-icon>
        <div class="upload-text">点击上传图片</div>
      </el-upload>

      <div class="image-preview" v-if="files.length">
        <img 
          v-for="(file, index) in files" 
          :key="index" 
          :src="file.url" 
          :alt="file.name"
        >
      </div>

      <div class="settings-area">
        <el-form-item label="动画速度">
          <el-slider 
            v-model="speed" 
            :min="1" 
            :max="10" 
            :step="1" 
            :format-tooltip="value => `${value}帧/秒`"
            show-stops
          />
        </el-form-item>

        <el-form-item label="输出尺寸">
          <el-radio-group v-model="size">
            <el-radio-button label="原图尺寸">原图尺寸</el-radio-button>
            <el-radio-button label="720P">720P</el-radio-button>
            <el-radio-button label="360P">360P</el-radio-button>
            <el-radio-button label="240P">240P</el-radio-button>
          </el-radio-group>
        </el-form-item>
      </div>

      <div class="button-group">
        <el-button 
          type="primary" 
          @click="generateGif" 
          :loading="isGenerating"
          :disabled="files.length < 2"
        >
          <el-icon><VideoPlay /></el-icon>
          生成GIF
        </el-button>
        <el-button 
          type="success" 
          @click="downloadGif" 
          :disabled="!gifUrl"
        >
          <el-icon><Download /></el-icon>
          下载GIF
        </el-button>
        <el-button @click="clearAll">
          <el-icon><Delete /></el-icon>
          清空
        </el-button>
        <el-button type="warning" @click="goToHomepage">
          <el-icon><Back /></el-icon>
          返回
        </el-button>
      </div>

      <div class="result-preview" v-if="gifUrl">
        <h3>预览：</h3>
        <img :src="gifUrl" alt="Generated GIF">
      </div>

      <div class="notes">
        <h3>帮助说明：</h3>
        <ul>
          <li>支持多张图片上传，建议图片大小和尺寸相近</li>
          <li>可调整动画速度，数值越大动画越快</li>
          <li>提供多种输出尺寸选择，可根据需要调整</li>
          <li>生成过程在本地完成，不会上传服务器</li>
          <li>建议上传的图片数量不超过20张</li>
          <li>支持PNG、JPG、JPEG等常见图片格式</li>
        </ul>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Plus, VideoPlay, Download, Delete, Back } from '@element-plus/icons-vue'
import GIF from 'gif.js'

const router = useRouter()
const files = ref([])
const speed = ref(5)
const size = ref('原图尺寸')
const gifUrl = ref('')
const isGenerating = ref(false)

const handleFileChange = (file, fileList) => {
  if (fileList.length > 20) {
    ElMessage.warning('最多只能上传20张图片')
    return
  }

  files.value = fileList.map(f => ({
    name: f.name,
    url: URL.createObjectURL(f.raw),
    raw: f.raw
  }))
}

const loadImage = (src) => {
  return new Promise((resolve, reject) => {
    const img = new Image()
    img.onload = () => resolve(img)
    img.onerror = reject
    img.src = src
  })
}

const generateGif = async () => {
  if (files.value.length < 2) {
    ElMessage.warning('请至少上传两张图片')
    return
  }

  isGenerating.value = true
  ElMessage.info('正在生成GIF，请稍候...')

  try {
    const gif = new GIF({
      workers: 2,
      quality: 10,
      width: size.value === '720P' ? 1280 : 
             size.value === '360P' ? 640 : 
             size.value === '240P' ? 426 : null,
      height: size.value === '720P' ? 720 : 
              size.value === '360P' ? 360 : 
              size.value === '240P' ? 240 : null,
      workerScript: '/gif.worker.js'
    })

    for (const file of files.value) {
      const img = await loadImage(file.url)
      gif.addFrame(img, { delay: 1000 / speed.value })
    }

    gif.on('finished', blob => {
      gifUrl.value = URL.createObjectURL(blob)
      isGenerating.value = false
      ElMessage.success('GIF生成成功')
    })

    gif.render()
  } catch (error) {
    isGenerating.value = false
    ElMessage.error('GIF生成失败，请重试')
    console.error('GIF generation error:', error)
  }
}

const downloadGif = () => {
  if (!gifUrl.value) return

  const link = document.createElement('a')
  link.href = gifUrl.value
  link.download = `animated_${new Date().getTime()}.gif`
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
  ElMessage.success('下载开始')
}

const clearAll = () => {
  files.value = []
  gifUrl.value = ''
  speed.value = 5
  size.value = '原图尺寸'
  ElMessage.success('已清空')
}

const goToHomepage = () => {
  router.push('/')
}
</script>

<style lang="scss" scoped>
.image-to-gif-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
  box-sizing: border-box;
  display: flex;
  justify-content: center;
  align-items: flex-start;
  overflow-y: auto;

  .gif-container {
    max-width: 800px;
    width: 96%;
    background-color: rgba(255, 255, 255, 0.95);
    border-radius: 20px;
    box-shadow: 0 15px 30px rgba(0, 0, 0, 0.2);
    padding: 30px;
    box-sizing: border-box;
    margin: 10px auto;

    h1 {
      text-align: center;
      color: #4a5568;
      font-size: 28px;
      margin-bottom: 30px;
      text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.1);
    }

    .upload-area {
      :deep(.el-upload--picture-card) {
        width: 100%;
        height: 150px;
        line-height: 150px;
        background-color: #f8fafc;
        border: 2px dashed #dcdfe6;
        border-radius: 12px;

        &:hover {
          border-color: #409EFF;
          background-color: rgba(64, 158, 255, 0.05);
        }

        .el-icon {
          font-size: 28px;
          color: #8c939d;
          margin-bottom: 8px;
        }

        .upload-text {
          color: #606266;
          font-size: 14px;
        }
      }
    }

    .image-preview {
      display: flex;
      flex-wrap: wrap;
      gap: 10px;
      margin: 20px 0;

      img {
        width: 100px;
        height: 100px;
        object-fit: cover;
        border-radius: 8px;
        box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
      }
    }

    .settings-area {
      margin: 20px 0;

      .el-form-item {
        margin-bottom: 20px;

        :deep(.el-form-item__label) {
          color: #4a5568;
          font-weight: 500;
        }

        .el-slider {
          margin-top: 10px;
        }

        .el-radio-group {
          display: flex;
          flex-wrap: wrap;
          gap: 10px;
        }
      }
    }

    .button-group {
      display: flex;
      gap: 15px;
      flex-wrap: wrap;
      justify-content: center;
      margin: 30px 0;

      .el-button {
        min-width: 120px;
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 8px;
        padding: 12px 20px;
        font-size: 14px;
        border-radius: 8px;
        transition: all 0.3s ease;

        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
        }

        .el-icon {
          font-size: 16px;
        }
      }
    }

    .result-preview {
      margin-top: 30px;
      text-align: center;

      h3 {
        color: #4a5568;
        margin-bottom: 15px;
      }

      img {
        max-width: 100%;
        border-radius: 8px;
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
      }
    }

    .notes {
      margin-top: 40px;
      padding: 20px;
      background-color: #f0f5ff;
      border-radius: 12px;
      color: #606266;
      text-align: left;

      h3 {
        color: #409EFF;
        margin: 0 0 15px 0;
        font-size: 16px;
        text-align: left;
      }

      ul {
        margin: 0;
        padding-left: 0;
        list-style-type: none;
        text-align: left;

        li {
          margin-bottom: 12px;
          line-height: 1.6;
          position: relative;
          padding-left: 18px;
          text-align: left;

          &:before {
            content: "•";
            color: #409EFF;
            font-size: 18px;
            position: absolute;
            left: 0;
            top: -2px;
          }

          &:last-child {
            margin-bottom: 0;
          }
        }
      }
    }
  }
}

@media (max-width: 768px) {
  .image-to-gif-page {
    padding: 10px;

    .gif-container {
      padding: 20px;
      width: 100%;

      h1 {
        font-size: 24px;
        margin-bottom: 20px;
      }

      .upload-area {
        :deep(.el-upload--picture-card) {
          height: 120px;
          line-height: 120px;
        }
      }

      .settings-area {
        .el-radio-group {
          flex-direction: column;
        }
      }

      .button-group {
        flex-direction: column;
        gap: 10px;

        .el-button {
          width: 100%;
          margin: 0;
        }
      }

      .notes {
        padding: 15px;
        margin-top: 30px;

        h3 {
          font-size: 15px;
        }

        ul li {
          font-size: 13px;
          margin-bottom: 8px;
        }
      }
    }
  }
}
</style>
